package com.yuyou.train.user.controller;

import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.vo.resp.RespUserPointsTop;
import com.yuyou.train.user.vo.resp.RespUserRaiseTop;
import com.yuyou.train.user.vo.resp.RespUserRank;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.ReturnResult;
import com.yuyou.train.util.enums.user.UserPraiseEnums;
import com.yuyou.train.util.tool.BeanUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.train.user.service.IUserPointsService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Validated
@RestController
@RequestMapping(value="/api/userPoints")
public class UserPointsController extends BaseController{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IUserPointsService userPointsService;

	@Autowired
	private IUserService userService;

	@ApiOperation(value = "积分排行榜(前台)")
	@RequestMapping(value="/findUserPointsTop", method = RequestMethod.POST)
	public ReturnResult<RespUserRank> findUserPointsTop(HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());

		List<RespUserPointsTop> userPointsTopList = userPointsService.findUserPointsTop(user.getClassId());
		Integer myRank = userPointsService.myRank(user.getClassId(), user.getId());

		// 处理积分数一样时排名问题
		List<String> userIds = BeanUtils.toList(userPointsTopList, "userId");
		if(!StringUtils.isEmpty(userIds) && !StringUtils.isEmpty(userPointsTopList) && userIds.contains(user.getId())){
			for(int i = 0; i < userPointsTopList.size(); i++){
				if(user.getId().equals(userPointsTopList.get(i).getUserId())){
					myRank = i + 1;
					break;
				}
			}
		}

		RespUserRank respUserRank = new RespUserRank();
		respUserRank.setUserPointsTopList(userPointsTopList);
		respUserRank.setMyRank(myRank);
		return ReturnResult.success(respUserRank);
	}

}
